package com.example.hospitalsystemclient.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hospitalsystemclient.Dataclass.UrlData;
import com.example.hospitalsystemclient.MainActivity;
import com.example.hospitalsystemclient.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class LoginActivity extends Activity {

    private EditText editTextName;
    private EditText editTextPassword;
    private Button buttonLogin;
    private UrlData urlData = new UrlData();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login); // 设置布局文件

        // 初始化组件
        editTextName = findViewById(R.id.editTextTextPersonName);
        editTextPassword = findViewById(R.id.editTextTextPassword);
        buttonLogin = findViewById(R.id.login);

        // 设置登录按钮的点击事件
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的用户名和密码
                String name = editTextName.getText().toString();
                String password = editTextPassword.getText().toString();

                if (!name.isEmpty() && !password.isEmpty()) {
                    // 创建一个 JSON 请求体
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("patientPhone", name);
                        jsonObject.put("patientPassword", password);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    // 创建一个请求体
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());

                    // 创建一个 POST 请求
                    Request request = new Request.Builder()
                            .url(urlData.Login())
                            .post(requestBody)
                            .build();

                    // 创建 OkHttp 客户端并执行请求
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            // 请求失败
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "网络问题", Toast.LENGTH_SHORT).show();
                                }
                            });
                            e.printStackTrace(); // 打印异常堆栈跟踪，以获取更多信息
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            // 请求成功
                            if (response.isSuccessful()) {
                                // 在主线程中处理响应
                                final String responseData = response.body().string();

                                try {
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    boolean stat = jsonObject.getBoolean("stat");

                                    if (stat) {
                                        // 登录成功，处理 datas
                                        JSONObject datasObject = jsonObject.getJSONObject("datas");
                                        String patientIdentify = datasObject.getString("patientIdentify");
                                        String patientName = datasObject.getString("patientName");
                                        int patientId = datasObject.getInt("patientId");
                                        String patientGender = datasObject.getString("patientGender");
                                        int patientAge = datasObject.getInt("patientAge");
                                        String patientAddr = datasObject.getString("patientAddr");
                                        String patientPhone = datasObject.getString("patientPhone");

                                        // 存储到 SharedPreferences
                                        SharedPreferences sharedPreferences = getSharedPreferences("localData", MODE_PRIVATE);
                                        SharedPreferences.Editor editor = sharedPreferences.edit();
                                        editor.putString("patientIdentify", patientIdentify);
                                        editor.putString("patientName", patientName);
                                        editor.putInt("patientId", patientId);
                                        editor.putString("patientGender", patientGender);
                                        editor.putInt("patientAge", patientAge);
                                        editor.putString("patientAddr", patientAddr);
                                        editor.putString("patientPhone", patientPhone);
                                        editor.apply();

                                        // 显示成功消息
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(LoginActivity.this, "登录成功: " + patientName, Toast.LENGTH_SHORT).show();
                                                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }
                                        });
                                    } else {
                                        // 登录失败，显示错误消息
                                        String message = jsonObject.getString("message");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(LoginActivity.this, "登录失败: " + message, Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this, "解析错误", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            } else {
                                // 服务器返回错误状态码
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(LoginActivity.this, "登录失败: " + response.message(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                } else {
                    // 登录失败，提示用户
                    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        TextView regisText = findViewById(R.id.Regis);
        String text = "<u>注册</u>";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            regisText.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));
        } else {
            regisText.setText(Html.fromHtml(text));
        }
        regisText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }
}